package com.zwzc.handler;

import com.alibaba.fastjson.JSON;
import com.zwzc.RedisConstants;
import com.zwzc.RedisUtil;
import com.zwzc.module.common.JsonResult;
import com.zwzc.module.sys.entity.SysMenu;
import com.zwzc.module.sys.entity.SysUser;
import com.zwzc.sys.SysUserFeign;
import com.zwzc.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ProjectName: zwzc
 * @ClassName: LocalAuthenticationSuccessHandler
 * @Author: hejialun
 * @Description: 登录成功处理
 * @Date: 2021/6/21 15:35
 */
@Component
public class LocalAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysUserFeign sysUserFeign;
    //过期时间
    @Value("${jwt.expireTime:3600}")
    public long EXPIRE_TIME;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //登录成功
        User user = (User) authentication.getPrincipal();

        SysUser sysUser = JSON.parseObject(JSON.toJSONString(sysUserFeign.getUserInfoByUsernameAll(user.getUsername()).getData()), SysUser.class);
        //吧用户信息存到token里面
        Map<String, Object> jwtMap = new HashMap<>();
        jwtMap.put("id", sysUser.getId());                   //设置用户id
        jwtMap.put("username", sysUser.getUsername());       //设置用户名
        jwtMap.put("password", sysUser.getPassword());       //设置用户密码
        String jwtToken = JwtUtils.sign(jwtMap);
        //将当前用户的权限缓存下来
        Map<String, String> roleMap = new HashMap<>();
        //设置角色权限
        roleMap.put(RedisConstants.SYS_ROLE_CODES, String.join(",", sysUser.getRoles()));
        //设置菜单
        roleMap.put(RedisConstants.SYS_MENU_CODES, sysUser.getSysMenusNoTree().stream().map(SysMenu::getCode).collect(Collectors.joining(",")));

        //将用户信息存到redis
        redisUtil.set(RedisConstants.USER_INFOS_PREFIX + jwtToken, jwtMap, EXPIRE_TIME);
        //将用户权限信息存到redis
        redisUtil.set(RedisConstants.USER_ROLE + sysUser.getUsername(), roleMap, EXPIRE_TIME);

        //吧用户信息返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("userInfo", sysUser);
        map.put("token", jwtToken);
        response.getWriter().print(JSON.toJSONString(JsonResult.success(map)));
    }

}